//
//  LeftViewController.m
//  Commerce
//
//  Created by xiaofeifei on 15/1/30.
//  Copyright (c) 2015年 fei. All rights reserved.
//

#import "LeftViewController.h"
#import "HomeViewController.h"
#import "SendMsgViewController.h"
#import "OwnerCompleteViewController.h"
#import "ShipperCompleteViewController.h"
#import "LogisticsCompleteViewController.h"
#import "ShortOwnerSendMsgViewController.h"
#import "LongOwnerSendMsgViewController.h"
#import "SpecialLineViewController.h"
#import "ShortListViewController.h"
#import "LoginViewController.h"
#import "AmbitusListViewController.h"
#import "SpeclalLineListViewController.h"
#import "OrderListViewController.h"
#import "WaitingOrderViewController.h"
#import "AmbitusAPPViewController.h"
#import "GoodsBookViewController.h"
#import "DDMenuController.h"
#import "LeftCell.h"
#import "PushViewController.h"

@interface LeftViewController (){
    AppDelegate *app;
    NSArray *_dataArray;
    NSArray *_sendOwnerArray;
    UIView *_detailBgView;
    UITableView *_detailTable;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation LeftViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [self.tableView setTableFooterView:view];
    
    _sendOwnerArray = @[@"发布短驳车源",@"发布长驳车源",@"发布特种车源"];
    
    id datadic;
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"LeftMenu"] != nil) {
        NSError *error = nil;
       datadic = [NSJSONSerialization
                      
                      JSONObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"LeftMenu"]
                      
                      options:NSJSONReadingMutableLeaves
                      
                      error:&error];
        _dataArray = datadic;
    }
    if (_dataArray.count == 0 || [[GlobalData sharedGlobalData] isNewLeft]) {
        [self getLeftMenu];
    }
    
    [self configUI];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [_footerView setFrame:CGRectMake(0, self.view.frame.size.height - 38, self.view.frame.size.width, 38)];
    
}

- (void)configUI{
    //可选项
    _detailBgView = [[UIView alloc] initWithFrame:self.view.bounds];
    [_detailBgView setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:_detailBgView];
    
    UIControl *bgView = [[UIControl alloc] initWithFrame:_detailBgView.bounds];
    [bgView setBackgroundColor:[UIColor blackColor]];
    [bgView setAlpha:0.5];
    [bgView addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
    [_detailBgView addSubview:bgView];
    
    _detailTable = [[UITableView alloc] initWithFrame:CGRectMake(40, 200, 220, 120)];
    [_detailTable setDelegate:self];
    [_detailTable setDataSource:self];
    [_detailBgView addSubview:_detailTable];
    
//    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _detailTable.frame.size.width , 25)];
//    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 3, 200, 16)];
//    label.text = @"车源发布";
//    label.textColor = RGB(0, 30, 255);
//    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(15, 24, headView.frame.size.width, 1)];
//    [line setBackgroundColor:RGB(0, 30, 255)];
//    [headView addSubview:line];
//    [headView addSubview:label];
//    [_detailTable setTableHeaderView:headView];
    
    [_detailBgView setHidden:YES];
}

- (void)cancel{
    [_detailBgView setHidden:YES];
}

#pragma mark -请求接口
- (void)getLeftMenu{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *parameters = [GlobalData paramterDic];
    [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@sys/leftmenu",URL_ROOT]
                                    params:parameters
                               requestMode:DGHTTPMethodPOST
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  NSData *jsonData = [NSJSONSerialization dataWithJSONObject:result options:NSJSONWritingPrettyPrinted error:nil];

                                  [[NSUserDefaults standardUserDefaults] setObject:jsonData forKey:@"LeftMenu"];
                                  
                                  _dataArray = result;
                                  [_tableView reloadData];
                                  
                                  [SVProgressHUD dismiss];
                              }];
}

#pragma mark - Table View Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_tableView == tableView) {
        return _dataArray.count;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_tableView == tableView) {
        return [_dataArray[section][@"Child"] count];
    }
    return _sendOwnerArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 25;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (_tableView == tableView) {
        UIView *view= [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 25)];
        UIImageView *bgImg = [[UIImageView alloc] initWithFrame:view.frame];
        [bgImg setImage:[UIImage imageNamed:@"headcell_bg.png"]];
        [view addSubview:bgImg];
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 2, 200, 20)];
        [titleLabel setTextColor:[UIColor whiteColor]];
        titleLabel.text = _dataArray[section][@"MenuName"];
        [view addSubview:titleLabel];
        
        return view;
    }else{
        UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _detailTable.frame.size.width , 25)];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 5, 200, 16)];
        label.text = @"车源发布";
        label.textColor = RGB(0, 30, 255);
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(15, 24, headView.frame.size.width, 1)];
        [line setBackgroundColor:RGB(0, 30, 255)];
        [headView addSubview:line];
        [headView addSubview:label];
        return headView;
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_tableView == tableView) {
        return 40;
    }
    return 30;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_tableView == tableView) {
        static NSString *CellIdentifier = @"Cell";
        
        LeftCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"LeftCell" owner:self options:nil];
            cell = (LeftCell *)[array objectAtIndex:0];
            cell.backgroundColor = [UIColor grayColor];
        }

        [cell configUIWithData:_dataArray[indexPath.section][@"Child"][indexPath.row]];
        
        return cell;
    }else {
        static NSString *CellIdentifier = @"Cell1";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            [cell setAccessoryType:UITableViewCellAccessoryNone];
        }
        cell.textLabel.text = _sendOwnerArray[indexPath.row];
        
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
   
    DDMenuController *menuController = (DDMenuController*)((AppDelegate*)[[UIApplication sharedApplication] delegate]).menuController;
    UIViewController *vc = nil;
    if (_tableView == tableView) {
        NSString *item = _dataArray[indexPath.section][@"Child"][indexPath.row][@"MenuName"];
        int menuID = [_dataArray[indexPath.section][@"Child"][indexPath.row][@"MenuID"] intValue];
        if (menuID == 4) {//货源发布
            if ([[GlobalData sharedGlobalData] userinfoDic] == nil) {
                [SVProgressHUD showInfoWithStatus:@"请先登录"];
                vc = [[LoginViewController alloc] initWithNibName:nil bundle:nil];
            }else if ([[GlobalData sharedGlobalData] userinfoDic][@"TrueName"] == [NSNull null]){
                int userType = [[[GlobalData sharedGlobalData] userinfoDic][@"UserType"] intValue];
                if (userType == 0) {
                    vc = [[OwnerCompleteViewController alloc] initWithNibName:nil bundle:nil];
                }else if (userType == 1) {
                    vc = [[ShipperCompleteViewController alloc] initWithNibName:nil bundle:nil];
                }
                else if (userType == 2) {
                    vc = [[LogisticsCompleteViewController alloc] initWithNibName:nil bundle:nil];
                }
            }else{
                if ([[[GlobalData sharedGlobalData] userinfoDic][@"State"] intValue] == 0) {
                    [SVProgressHUD showInfoWithStatus:@"用户信息正在审核中"];
                    return;
                }else{
                    vc = [[SendMsgViewController alloc] initWithNibName:nil bundle:nil];
                }
            }
        }
        else if (menuID == 7) {//车源发布
            if ([[GlobalData sharedGlobalData] userinfoDic] == nil) {
                [SVProgressHUD showInfoWithStatus:@"请先登录"];
                vc = [[LoginViewController alloc] initWithNibName:nil bundle:nil];
            }else if ([[GlobalData sharedGlobalData] userinfoDic][@"TrueName"] == [NSNull null]){
                int userType = [[[GlobalData sharedGlobalData] userinfoDic][@"UserType"] intValue];
                if (userType == 0) {
                    vc = [[OwnerCompleteViewController alloc] initWithNibName:nil bundle:nil];
                }else if (userType == 1) {
                    vc = [[ShipperCompleteViewController alloc] initWithNibName:nil bundle:nil];
                }
                else if (userType == 2) {
                    vc = [[LogisticsCompleteViewController alloc] initWithNibName:nil bundle:nil];
                }
            }else{
                if ([[[GlobalData sharedGlobalData] userinfoDic][@"State"] intValue] == 0) {
                    [SVProgressHUD showInfoWithStatus:@"用户信息正在审核中"];
                    return;
                }else{
                    [_detailBgView setHidden:NO];
                    return;
                }
            }
        }
        else if (menuID == 8){//货源预定
            if ([[GlobalData sharedGlobalData] userinfoDic] == nil) {
                [SVProgressHUD showInfoWithStatus:@"请先登录"];
                vc = [[LoginViewController alloc] initWithNibName:nil bundle:nil];
            }else{
                vc = [[GoodsBookViewController alloc] initWithNibName:nil bundle:nil];
            }
        }
        else if (menuID == 29){//即时货源
            [menuController showRootController:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"HomeList" object:@{@"menu":@"0",@"name":item}];
            return;
        }else if (menuID == 5){//即时车源
            [menuController showRootController:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"HomeList" object:@{@"menu":@"1",@"name":item}];
            return;
        }else if (menuID == 11){//专线查询
            vc = [[SpecialLineViewController alloc] initWithNibName:nil bundle:nil];
        }else if (menuID == 12){//分流仓储
//            vc = [[SpecialLineViewController alloc] initWithNibName:nil bundle:nil];
            return;
        }
        else if (menuID == 6){//短驳配送
            vc = [[ShortListViewController alloc] initWithNibName:nil bundle:nil];
        }else if (menuID == 9){//周边维修
            vc = [[AmbitusListViewController alloc] initWithNibName:nil bundle:nil];
            [(AmbitusListViewController *)vc setNavStr:item];
//            [self presentViewController:vc animated:YES completion:^{
//                
//            }];
//            return;
        }else if (menuID == 10){//品牌专线
            vc = [[SpeclalLineListViewController alloc] initWithNibName:nil bundle:nil];
        }else if (menuID == 16){//周边应用
            vc = [[AmbitusAPPViewController alloc] initWithNibName:nil bundle:nil];
            [(AmbitusAPPViewController *)vc setNavStr:item];
            [self presentViewController:vc animated:YES completion:^{
                
            }];
            return;
        }
        else if (menuID == 26 ||menuID == 30){//等待确认订单
            if ([[GlobalData sharedGlobalData] userinfoDic] == nil) {
                [SVProgressHUD showInfoWithStatus:@"请先登录"];
                vc = [[LoginViewController alloc] initWithNibName:nil bundle:nil];
            }else{
                vc = [[WaitingOrderViewController alloc] initWithNibName:nil bundle:nil];
                [(WaitingOrderViewController *)vc setMenuID:menuID];
            }
        }
        else if (menuID == 27||menuID == 31){//我的订单 车源订单
            if ([[GlobalData sharedGlobalData] userinfoDic] == nil) {
                [SVProgressHUD showInfoWithStatus:@"请先登录"];
                vc = [[LoginViewController alloc] initWithNibName:nil bundle:nil];
            }else{
                vc = [[OrderListViewController alloc] initWithNibName:nil bundle:nil];
                [(OrderListViewController *)vc setMenuID:menuID];
            }
        }
        else if (menuID == 33){//推送记录
            if ([[GlobalData sharedGlobalData] userinfoDic] == nil) {
                [SVProgressHUD showInfoWithStatus:@"请先登录"];
                vc = [[LoginViewController alloc] initWithNibName:nil bundle:nil];
            }else{
                vc = [[PushViewController alloc] initWithNibName:nil bundle:nil];
            }
        }
        [(BasicViewController *)vc setNavStr:item];
    }else{//选择短驳或长驳
        [_detailBgView setHidden:YES];
        if (indexPath.row == 0) {//短驳
            vc = [[ShortOwnerSendMsgViewController alloc] initWithNibName:nil bundle:nil];
        }else if (indexPath.row == 1){//长驳
            vc = [[LongOwnerSendMsgViewController alloc] initWithNibName:nil bundle:nil];
            [(LongOwnerSendMsgViewController *)vc setLine_type:@"1"];
        }else if (indexPath.row == 2){//特种车
            vc = [[LongOwnerSendMsgViewController alloc] initWithNibName:nil bundle:nil];
            [(LongOwnerSendMsgViewController *)vc setLine_type:@"2"];
        }
        [(BasicViewController *)vc setNavStr:@"车源发布"];
    }
    
    UINavigationController *navController = (UINavigationController*)((AppDelegate*)[[UIApplication sharedApplication] delegate]).menuController;
    [navController pushViewController:vc animated:YES];
    [menuController showRootController:NO];
}

- (IBAction)callphone:(id)sender{
    [[GlobalData sharedGlobalData] phoneBtnActWithNum:@"4009605288"];
    //传入的参数
    NSString *user_name = [[GlobalData sharedGlobalData] userinfoDic][@"UserName"];
    if (!user_name) {
        user_name = @"";
    }
    NSString *url = [NSString stringWithFormat:@"%@user/boda?api_key=%@&user_name=%@&to_username=%@",URL_ROOT,[[@"1234567890!@#" md5HexDigest] uppercaseString],user_name,@"4009605288"];
    NSMutableDictionary *parameters = [GlobalData paramterDic];
    [[BaseNetwork alloc] initWithMethodUrl:url
                                    params:parameters
                               requestMode:DGHTTPMethodGET
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                              }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
